﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxGridView;
using TireService.Data;
using DevExpress.Web.ASPxEditors;
using System.Web.Security;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxPanel;

namespace TireService.Web.UserControls
{
    public partial class ucEditCar : System.Web.UI.UserControl
    {
        private string _controlname = "EditCustomerCar";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Convert.ToBoolean(Session["UserControlLoaded" + _controlname]))
            {
                // Initiate datalayer
                TireServiceDB db = new TireServiceDB();

                // Show customer subscriptions
                LoadCustomerCar(Convert.ToInt32(Session["CustomerId" + _controlname]), db);
            }  
        }

        protected void callbackEditCustomerCarPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            Session["CustomerId" + _controlname] = Convert.ToInt32(e.Parameter);

            LoadUserControl(Convert.ToInt32(e.Parameter));
        }

        /// <summary>
        /// Public function for loading usercontrol
        /// </summary>
        public void LoadUserControl(int CustomerId)
        {
            // Initiate datalayer
            TireServiceDB db = new TireServiceDB();

            if (CustomerId != 0)
            {
                // Show customer cars
                LoadCustomerCar(CustomerId, db);
            }
            else
            {
                // Error
                throw new ArgumentException("Kunde ikke fundet");
            }

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// Function that bind customer car to gridview
        /// </summary>
        /// <param name="CustomerId">Id for customer</param>
        /// <param name="db">Connection to database</param>
        private void LoadCustomerCar(int CustomerId, TireServiceDB db)
        {
            List<CustomerSubscriptionView> customersubscription = db.GetCustomerSubscriptionViews(CustomerId);
            //List<BusinessSubscriptionListView> customersubscription = db.GetCustomerBusinessSubscriptions(CustomerId, false);
            List<BusinessCarListView> cars = db.GetCustomerCarsAll(CustomerId, cbShowChildCars.Checked);

            // Bind to gridview
            gvCar.DataSource = cars;
            gvCar.DataBind();

            //gvCar.ClearSort();
            //gvCar.GroupSummary.Clear();
            //gvCar.GroupBy(gvCar.Columns["CustomerSubscriptionId"]);
            //gvCar.ExpandAll();

            // Prepare data for editmode of customer car
            GridViewDataComboBoxColumn ddlCarSubscription = gvCar.Columns["CustomerSubscriptionDropdown"] as GridViewDataComboBoxColumn;
            ddlCarSubscription.PropertiesComboBox.ValueType = typeof(int);
            ddlCarSubscription.PropertiesComboBox.DataSource = customersubscription;
            ddlCarSubscription.PropertiesComboBox.TextField = "Description";
            ddlCarSubscription.PropertiesComboBox.ValueField = "CustomerSubscriptionId";
            ddlCarSubscription.PropertiesComboBox.TextFormatString = "{0}-{1}";

            // Prepare data for editmode of customer car
            GridViewDataComboBoxColumn ddlCarBrand = gvCar.Columns["CarBrandDropdown"] as GridViewDataComboBoxColumn;
            ddlCarBrand.PropertiesComboBox.ValueType = typeof(int);
            ddlCarBrand.PropertiesComboBox.DataSource = db.GetCarBrand();
            ddlCarBrand.PropertiesComboBox.TextField = "Description";
            ddlCarBrand.PropertiesComboBox.ValueField = "CarBrandId";
            ddlCarBrand.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlCarBrand.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlCarStatus = gvCar.Columns["CarStatusDropdown"] as GridViewDataComboBoxColumn;
            ddlCarStatus.PropertiesComboBox.ValueType = typeof(int);
            ddlCarStatus.PropertiesComboBox.DataSource = db.GetCarStatus();
            ddlCarStatus.PropertiesComboBox.TextField = "Description";
            ddlCarStatus.PropertiesComboBox.ValueField = "CarStatusId";
            ddlCarStatus.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlCarStatus.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlFuelType = gvCar.Columns["FuelTypeDropdown"] as GridViewDataComboBoxColumn;
            ddlFuelType.PropertiesComboBox.ValueType = typeof(int);
            ddlFuelType.PropertiesComboBox.Items.Clear();
            ddlFuelType.PropertiesComboBox.Items.Add("Benzin", 0);
            ddlFuelType.PropertiesComboBox.Items.Add("Diesel", 1);
            ddlFuelType.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlFuelType.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            //// Prepare data for editmode of customer tireset
            //GridViewDataComboBoxColumn ddlCar = gvTireSet.Columns["CarDropdown"] as GridViewDataComboBoxColumn;
            //ddlCar.PropertiesComboBox.ValueType = typeof(int);
            //ddlCar.PropertiesComboBox.Columns.Add("RegistrationNumber", "Reg.nr");
            //ddlCar.PropertiesComboBox.Columns.Add("Model", "Model");
            //ddlCar.PropertiesComboBox.Columns.Add("Year", "Årgang");
            //ddlCar.PropertiesComboBox.Columns.Add("Color", "Farve");
            //ddlCar.PropertiesComboBox.DataSource = cars;
            ////ddlCar.PropertiesComboBox.TextField = "Description";
            //ddlCar.PropertiesComboBox.ValueField = "CarId";
            //ddlCar.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            //ddlCar.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            Session["UserControlLoaded" + _controlname] = true;
        }

        protected void ddlNewContainer_Callback(object source, CallbackEventArgsBase e)
        {
            TireServiceDB db = new TireServiceDB();

            ASPxPanel pCargoRoom = (ASPxPanel)gvCar.FindEditFormTemplateControl("pCargoRoom");

            int ContainerId;

            ASPxComboBox ddlNewContainer = (ASPxComboBox)pCargoRoom.FindControl("ddlNewContainer");

            ddlNewContainer.TextField = "ContainerNumber";
            ddlNewContainer.ValueField = "ContainerId";
            ddlNewContainer.DataSource = db.GetContainers();
            ddlNewContainer.DataBind();
            ddlNewContainer.SelectedIndex = 0;

            FillNewContainerCargoRoom(Convert.ToInt32(ddlNewContainer.SelectedItem.Value), db);
        }

        protected void ddlNewContainerCargoRoom_Callback(object source, CallbackEventArgsBase e)
        {
            TireServiceDB db = new TireServiceDB();

            FillNewContainerCargoRoom(Convert.ToInt32(e.Parameter), db);
        }

        private void FillNewContainerCargoRoom(int ContainerId, TireServiceDB db) 
        {
            ASPxPanel pCargoRoom = (ASPxPanel)gvCar.FindEditFormTemplateControl("pCargoRoom");
            ASPxComboBox ddlNewContainerCargoRoom = (ASPxComboBox)pCargoRoom.FindControl("ddlNewContainerCargoRoom");
            ddlNewContainerCargoRoom.TextField = "CargoRoomNumber";
            ddlNewContainerCargoRoom.ValueField = "ContainerCargoRoomId";
            ddlNewContainerCargoRoom.DataSource = db.GetContainerCargoRoomTireSetViews(ContainerId).Where(p => p.TireSetId == null).OrderBy(p => p.CargoRoomNumber).ToList();
            ddlNewContainerCargoRoom.DataBind();
        }

        /// <summary>
        /// Postback function that updates gridview with cars
        /// </summary>
        protected void gvCar_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // Show cars
            LoadCustomerCar(Convert.ToInt32(Session["CustomerId" + _controlname]), db);
        }

        /// <summary>
        /// Gridview function for updating customer car
        /// </summary>
        protected void gvCar_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            if (Convert.ToInt32(Session["CustomerId" + _controlname]) != 0)
            {
                TireServiceDB db = new TireServiceDB();

                // Get id
                int CarId = Convert.ToInt32(e.Keys["CarId"]);

                // Fecth customer
                Customer customer = db.GetCustomer(Convert.ToInt32(Session["CustomerId" + _controlname]));
                CustomerSubscription customersubscription = db.GetCustomerSubscription(Convert.ToInt32(e.NewValues["CustomerSubscriptionId"]));

                Guid userid = new Guid(Membership.GetUser().ProviderUserKey.ToString());

                // Create car
                Car car = new Car();

                DateTime? lasttiresetchangedate = null;
                DateTime? nexttiresetchangeplanningdate = null;

                string model = "-";
                string enginesize = "-";

                if (e.NewValues["LastTireSetChangeDate"] != null) lasttiresetchangedate = Convert.ToDateTime(e.NewValues["LastTireSetChangeDate"]);
                if (e.NewValues["NextTireSetChangePlanningDate"] != null) nexttiresetchangeplanningdate = Convert.ToDateTime(e.NewValues["NextTireSetChangePlanningDate"]);

                if (e.NewValues["Model"] != null) model = Convert.ToString(e.NewValues["Model"]);
                if (e.NewValues["EngineSize"] != null) enginesize = Convert.ToString(e.NewValues["EngineSize"]);

                CarBLL carBLL = new CarBLL();
                carBLL.UpdateCar(
                                    db,
                                    car,
                                    customersubscription,
                                    customer,
                                    CarId,
                                    e.NewValues["RegistrationNumber"].ToString(),
                                    Convert.ToInt32(e.NewValues["CarBrandId"]),
                                    model,
                                    enginesize,
                                    Convert.ToInt32(e.NewValues["FuelType"]),
                                    0 + Convert.ToInt32(e.NewValues["Year"]),
                                    e.NewValues["Color"].ToString(),
                                    Convert.ToInt32(e.NewValues["CarStatusId"]),
                                    lasttiresetchangedate,
                                    nexttiresetchangeplanningdate,
                                    true
                                );

                // Commit changes to database
                db.SubmitChanges();

                // End edit mode
                e.Cancel = true;
                gvCar.CancelEdit();

                // Reset edit mode
                CarId = 0;

                // Refresh gridview and dropdownlist
                LoadCustomerCar(Convert.ToInt32(Session["CustomerId" + _controlname]), db);

                //if (CarId == 0)
                //{
                //    // Refresh tireset gridview
                //    BindTireSet(db, this.CustomerId);
                //}

                // Close db connection
                db.Dispose();
            }
            else
            {
                // Customer not yet saved
                throw new ArgumentException("Kunde data ikke gemt endnu - kunde bil kan derfor ikke oprettes. Venligst gem kundedata først.");
            }
        }

        /// <summary>
        /// Gridview function for creating customer car
        /// </summary>
        protected void gvCar_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            if (Convert.ToInt32(Session["CustomerId" + _controlname]) != 0)
            {
                TireServiceDB db = new TireServiceDB();

                // Set car id to zero - new car
                int CarId = 0;

                // Fecth customer
                Customer customer = db.GetCustomer(Convert.ToInt32(Session["CustomerId" + _controlname]));
                CustomerSubscription customersubscription = db.GetCustomerSubscription(Convert.ToInt32(e.NewValues["CustomerSubscriptionId"]));

                Guid userid = new Guid(Membership.GetUser().ProviderUserKey.ToString());

                // Create car
                Car car = new Car();

                DateTime? lasttiresetchangedate = null;
                DateTime? nexttiresetchangeplanningdate = null;
                string model = "-";
                string enginesize = "-";

                if (e.NewValues["LastTireSetChangeDate"] != null) lasttiresetchangedate = Convert.ToDateTime(e.NewValues["LastTireSetChangeDate"]);
                if (e.NewValues["NextTireSetChangePlanningDate"] != null) nexttiresetchangeplanningdate = Convert.ToDateTime(e.NewValues["NextTireSetChangePlanningDate"]);

                if (e.NewValues["Model"] != null) model = Convert.ToString(e.NewValues["Model"]);
                if (e.NewValues["EngineSize"] != null) enginesize = Convert.ToString(e.NewValues["EngineSize"]);

                CarBLL carBLL = new CarBLL();
                carBLL.UpdateCar(
                                    db,
                                    car,
                                    customersubscription,
                                    customer,
                                    CarId,
                                    e.NewValues["RegistrationNumber"].ToString(),
                                    Convert.ToInt32(e.NewValues["CarBrandId"]),
                                    model,
                                    enginesize,
                                    Convert.ToInt32(e.NewValues["FuelType"]),
                                    0 + Convert.ToInt32(e.NewValues["Year"]),
                                    e.NewValues["Color"].ToString(),
                                    Convert.ToInt32(e.NewValues["CarStatusId"]),
                                    lasttiresetchangedate,
                                    nexttiresetchangeplanningdate,
                                    true
                                );

                if (CarId == 0)
                {
                    // Add tiresets for new car
                    TireSet tireset1 = new TireSet();
                    TireSet tireset2 = new TireSet();
                    TireSetBLL tiresetBLL = new TireSetBLL();
                    ContainerCargoRoomBLL containerBLL = new ContainerCargoRoomBLL();

                    // Determine what tires are on the car
                    int tireset1status, tireset2status;
                    int? tireset1container, tireset2container;

                    ASPxRadioButtonList rblCurrentTireSet = (ASPxRadioButtonList)gvCar.FindEditFormTemplateControl("rblCurrentTireSet");

                    ASPxRadioButtonList rblOtherTireSet = (ASPxRadioButtonList)gvCar.FindEditFormTemplateControl("rblOtherTireSet");

                    int tiresetonstockstatus = (int)Shared.TireSetStatus.OnStock;

                    if (rblOtherTireSet.Value.ToString() == "0")
                    {
                        // Customer has tireset1
                        tiresetonstockstatus = (int)Shared.TireSetStatus.PlacedAtCustomer;
                    }
                    if (rblOtherTireSet.Value.ToString() == "1")
                    {
                        // Tirest should be picked up - get create task and get address
                        tiresetonstockstatus = (int)Shared.TireSetStatus.PlacedAtCustomer;
                        


                    }
                    if (rblOtherTireSet.Value.ToString() == "2")
                    {
                        // We already have the tireset
                        tiresetonstockstatus = (int)Shared.TireSetStatus.OnStock;

                        // TODO: Make code for selecting right container
                    }
                    

                    if (rblCurrentTireSet.Value.ToString() == "0")
                    {
                        // Winter tires on car
                        tireset1status = tiresetonstockstatus;
                        tireset1container = containerBLL.ReturnNearestContainerCargoRoomId(db, float.Parse(customer.LatitudePrimary.ToString()), float.Parse(customer.LongitudePrimary.ToString()));
                        tireset2status = (int)Shared.TireSetStatus.MountedOnCar;
                        tireset2container = null;
                    }
                    else
                    {
                        // Summer tires on car
                        tireset1status = (int)Shared.TireSetStatus.MountedOnCar;
                        tireset1container = null;
                        tireset2status = tiresetonstockstatus;
                        tireset2container = containerBLL.ReturnNearestContainerCargoRoomId(db, float.Parse(customer.LatitudePrimary.ToString()), float.Parse(customer.LongitudePrimary.ToString()));
                    }

                    tiresetBLL.UpdateTireSet(
                                        db,
                                        tireset1,
                                        car,
                                        (int)Shared.TireType.SummerTires,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        false,
                                        false,
                                        false,
                                        false,
                                        false,
                                        null,
                                        null,
                                        tireset1status,
                                        null,
                                        tireset1container,
                                        true,
                                        false,
                                        null,
                                        userid,
                                        null,
                                        true
                                    );

                    tiresetBLL.UpdateTireSet(
                                        db,
                                        tireset2,
                                        car,
                                        (int)Shared.TireType.WinterTires,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        false,
                                        false,
                                        false,
                                        false,
                                        false,
                                        null,
                                        null,
                                        tireset2status,
                                        null,
                                        tireset2container,
                                        true,
                                        false,
                                        null,
                                        userid,
                                        null,
                                        true
                                    );
                }

                // Commit changes to database
                db.SubmitChanges();

                // End edit mode
                e.Cancel = true;
                gvCar.CancelEdit();

                // Reset edit mode
                CarId = 0;

                // Refresh gridview and dropdownlist
                LoadCustomerCar(Convert.ToInt32(Session["CustomerId" + _controlname]), db);

                //if (this.CarId == 0)
                //{
                //    // Refresh tireset gridview
                //    BindTireSet(db, this.CustomerId);
                //}

                // Close db connection
                db.Dispose();
            }
            else
            {
                // Customer not yet saved
                throw new ArgumentException("Kunde data ikke gemt endnu - kunde bil kan derfor ikke oprettes. Venligst gem kundedata først.");
            }
        }
    }
}